<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button  class="el-icon-refresh" @click="refresh"></el-button>
          <el-button v-perm="'task'" type="success" size="small" @click="publishTask">发布任务</el-button>
          <el-date-picker
              v-model="value1"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
          </el-date-picker>
          <el-button type="primary" size="small" @click="keywordQuery">查询</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <!--    v-for中的变量为数据库返回的任务list集合，前端为数组[]-->
    <div>
      <ul class="task-list">
        <li v-for="(item, index) in taskMags" :key="item.id" class="task-item">
          <el-card class="box-card">
            <el-form :model="item" label-width="80px">
              <el-form-item label="任务标题:" class="el-form-item-title">
                {{ item.title }}
              </el-form-item>
              <el-form-item label="任务内容:" class="el-form-item-content ">
                <div class="content-text" >{{ item.content }}</div>
              </el-form-item>
              <el-form-item label="发布人:"class="el-form-item-people">
                {{ item.publisher }}
              </el-form-item>
              <el-form-item label="发布日期:"class="el-form-item-time">
                {{ item.time }}
              </el-form-item>
            </el-form>
              <el-popover placement="bottom" width="185">
                <el-button slot="reference" class="dropdown-button">操作</el-button>
                <div class="horizontal-menu" clearfix>
                  <el-button  v-perm="'task/showdata'" type="success" size="small" @click="handleView(index,item)">详情</el-button>
                  <el-button  v-perm="'task/upd'" type="primary" size="small" @click="handleEdit(index, item)">编辑</el-button>
                  <el-button v-perm="'task/del'"  type="danger" size="small" @click="handleDelete(index, item)">删除</el-button>
                </div>
              </el-popover>

          </el-card>
        </li>
      </ul>
    </div>

    <!-- 编辑页面 -->
    <el-dialog title="修改任务" :visible.sync="editFormVisible" :close-on-click-modal="false">
      <el-form :model="editForm" :rules="editFormRules" ref="editForm" label-width="80px">
        <el-form-item label="任务标题" prop="title">
          <el-input v-model="editForm.title" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="内容详情" prop="content">
          <el-input type="textarea" v-model="editForm.content" auto-complete="off" :rows="2"></el-input>
        </el-form-item>
        <el-form-item label="任务图片" prop="jpg">
          <el-image class="image-container" :src="editForm.jpg" fit="contain" style="max-width: 100%; max-height: 200px;"></el-image>
        </el-form-item>
        <el-form-item label="修改图片">
          <el-upload
              class="upload-demo"
              name="file"
              :action="this.$uploadURL"
              :on-remove="handleFileRemove"
              :on-success="handleFileUploadedit"
              :on-exceed="handleFileExceed"
              :file-list="fileList"
              :limit="1"
              accept=".jpg,.png,.gif"
              list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="执行人员" prop="executiveId">
          <el-select v-model="editForm.executiveId" placeholder="请选择" multiple>
            <el-option v-for="item in employees" :label="item.adminName" :value="item.id">
              <span style="float: left">{{ item.adminName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="截止日期" prop="endDate">
          <el-date-picker
              v-model="editForm.deadline"
              type="datetime"
              placeholder="请选择截止时间"
              default-time="23:59:59"
              :picker-options="{ disabledDate: disablePastDates }">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>
<!--    查看详情-->
    <el-dialog title="任务详情" :visible.sync="showFormVisible" :close-on-click-modal="false">
      <el-form :model="showForm" label-width="80px" :rules="showFormRules" ref="showForm">
        <hr class="custom-divider">
        <el-form-item label="标题:" >
          <span>{{ showForm.title}}</span>
        </el-form-item>
        <hr class="custom-divider">
        <el-form-item label="任务状态:" >
          <span :style="{ color: taskStatusColor }">{{taskStatus}}</span>
        </el-form-item>
        <hr class="custom-divider">
        <el-form-item label="任务内容:" >
          <span>{{showForm.content}}</span>
        </el-form-item>
        <hr class="custom-divider">
        <el-form-item label="图片:" >
          <el-image :src="showForm.jpg" fit="contain" style="max-width: 100%; max-height: 200px;"></el-image>
        </el-form-item>
        <hr class="custom-divider">
        <el-form-item label="执行人员:">
          <span>{{ getExecutiveNames(showForm.executiveId) }}</span>
        </el-form-item>
        <hr class="custom-divider">
        <el-row :gutter="24">
          <el-col :span="12">
        <el-form-item label="发布时间:" >
          <span>{{showForm.time}}</span>
        </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item label="截止日期:" >
          <span>{{showForm.deadline}}</span>
        </el-form-item>
          </el-col>
        </el-row>
        <hr class="custom-divider">
      </el-form>
        <div slot="footer" class="dialog-footer">
        <el-button @click.native="showFormVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!--    发布任务-->
    <el-dialog title="发布任务" :visible.sync="addFormVisible" :close-on-click-modal="false">
      <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
        <el-form-item label="任务标题" prop="title">
          <el-input v-model="addForm.title" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="任务内容">
          <el-input type="textarea" v-model="addForm.content" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="任务图片">
          <el-upload
              class="upload-demo"
              name="file"
              :action="this.$uploadURL"
              :on-remove="handleFileRemove"
              :on-success="handleFileUpload"
              :on-exceed="handleFileExceed"
              :file-list="fileList"
              :limit=1
              accept=".jpg,.png,.gif"
              list-type="picture">
            <!--              :headers="{ Authorization: 'Bearer ' + localStorage.getItem('token') }">-->
            <el-button size="small" type="primary">点击上传</el-button>
            <!--            <div slot="tip" class="el-upload__tip">只能上传指定类型图片文件，且不超过500kb</div>-->
          </el-upload>
        </el-form-item>
        <el-form-item label="执行人员" prop="executiveId">
          <el-select v-model="addForm.executiveId" placeholder="请选择" multiple>
            <el-option v-for="item in employees"
                       :label="item.adminName"
                       :value="item.id">
              <span style="float: left">{{ item.adminName  }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="截止日期" prop="endDate">
          <el-date-picker
              v-model="addForm.deadline"
              type="datetime"
              placeholder="选择日期"
              default-time="23:59:59">
          </el-date-picker>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click="addSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>


<script>
import util from "../../common/js/util";

export default {
  computed: {
    taskStatus() {
      const currentTime = new Date();
      const deadlineTime = new Date(this.showForm.deadline);

      if (currentTime > deadlineTime) {
        return '已过期';
      } else {
        return '进行中';
      }
    },
    taskStatusColor() {
      return this.taskStatus === '已过期' ? 'red' : 'green';
    },
  },
  data() {
    return {
      fileList: [],
      // 修改任务
      editFormVisible: false, // 编辑界面是否显示
      editForm: {
        publisher:'',//发布人
        //taskId:'',
        title: '',
        content: '',
        executiveId: [], // 确保是一个空数组
        jpg:'',
        deadline:'',
      },
      editLoading: false,
      editFormRules: {
        title: [
          { required: true, message: '请输入任务标题', trigger: 'blur' },
        ],
        content: [
          { required: true, message: '请输入任务内容', trigger: 'blur' },
        ],
        executiveId: [
          { required: true, message: '请选择执行人员', trigger: 'change' },
        ],
      },
//详情数据
      showFormVisible: false, // 编辑界面是否显示
      showForm: {
        publisher:'',
        taskId:'',
        title: '',
        content: '',
        executiveId: [], // 确保是一个空数组
        jpg:'',
        time:'',
        deadline:'',
      },
      showLoading: false,
      showFormRules: {
        title: [
          { required: true, message: '请输入任务标题', trigger: 'blur' },
        ],
        content: [
          { required: true, message: '请输入任务内容', trigger: 'blur' },
        ],
        executiveId: [
          { required: true, message: '请选择执行人员', trigger: 'change' },
        ],
      },

      //1.分页查询的相关数据
      departments: [],    //列表数据
      listLoading: false, //列表的加载框
      pageSize: 5,        //每页显示条数
      currentPage: 1,     //当前页
      totals: 0,          //总条数

      //2.高级查询相关数据
      keyword: '',
      //时间选择器

      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      taskMags: [],
      value1: '',
      value2: '',

      //4.添加任务
      addFormVisible: false,//控制对话框是都显示，默认为false
      addLoading: false, //加载框
      addFormRules: { // 表单项验证

      },
      addForm: {
        publisher:'',
        title:'',
        content:'',
        executiveId: [],
        jpg:'',
        time:'',
        deadline:null,
      },
      //执行人信息
      employees: [],
    }
  },
  methods: {

    //文件删除时的回调
    handleFileRemove(file, fileList) {
      //正式删除
      var fileName = null;
      if (file.response) {  //上传图片的时候点了删除
        fileName = file.response.resultObj;
      } else {  //点击修改回显的图片，点了删除
        fileName = file.url;
      }
      //为了方便参数传递,需要转换路径写法,把/替换为_
      fileName = fileName.replaceAll("/", "_");
      //发送请求
      this.$http.delete("/minio/" + fileName).then(res => {
        if (res.data.success) {
          this.$message.success("删除成功");
          this.fileList = [];
          this.addForm.jpg = "";
        } else {
          this.$message.error("删除失败");
        }
      })
    },

    //文件上传成功之后的回调
    handleFileUpload(response) {
      if (response.success) {
        this.addForm.jpg = response.resultObj;
      }
    },
    //文件上传成功之后的修改页面回调
    handleFileUploadedit(response) {
      if (response.success) {
        this.editForm.jpg = response.resultObj;
      }
    },
    //上传超过数量的回调
    handleFileExceed() {
      this.$message.error("不能上传多张图片");
    },

    //时间格式转换
    formatDateForBackend(dateTime) {
      const isoDateTime = new Intl.DateTimeFormat('sv-SE', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
      }).format(dateTime);

      return isoDateTime;
    },
    disablePastDates(time) {
      const currentDate = new Date();
      return time.getTime() < currentDate.getTime();
    },
    //页面刷新数据
    refresh() {
        // 点击按钮时，调用浏览器的刷新方法
        location.reload();
    },
//详情页面
    handleView(index,row) {
      this.showForm = Object.assign({},row);
      this.showFormVisible = true;
      this.getEmployee();
    },
    getExecutiveNames(executiveIds) {
      // 获取执行人员的名称
      const executiveNames = executiveIds.map(id => {
        const employee = this.employees.find(e => e.id === id);
        return employee ? employee.adminName : '';
      });
      // 过滤掉空字符串，然后以逗号分隔拼接成文本
      return executiveNames.filter(name => name).join(', ');
    },
//编辑数据
    handleEdit(index,row) {
      // 假设 row 是你要编辑的任务项
      this.editForm = Object.assign({},row);
      this.editFormVisible = true;
      this.getEmployee();
    },
    //删除数据
    handleDelete(index,row) {
      console.log("Deleting task with ID:", row.taskId);
        this.$confirm('确认删除该任务吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          const taskId = parseInt(row.taskId, 10); // 使用正确的属性
          this.$http.delete("/task/" + taskId).then(res => {
            if (res.data.success) {
              //计算总页数
              let totalPage = Math.ceil(this.total / this.pageSize);
              // 当删除最后一页的最后一条数据，并且当前不是第一页，就让当前页-1
              if (this.currentPage == totalPage && (this.total - 1) % this.pageSize == 0 && this.currentPage != 1) {
                this.currentPage = this.currentPage - 1;
              }
              this.$message({
                message: '删除成功',
                type: 'success'
              });
              this.findTaskMag();
            } else {
              this.$message.error("系统繁忙，请稍后重试!!!【500】");
            }
            this.listLoading = false;
          }).catch(res => {
            this.$message.error("系统繁忙，请稍后重试!!!【400,404】");
          })
        }).catch(() => {
        });
      },



    //3.关键字查询
    keywordQuery() {
      //假如当前页不在第一页，防止高级查询没有那么多页的时候出现空数据的问题
      // this.currentPage = 1;
      // this.getDepartments();
    },

    //发布任务
    publishTask: function () {
      this.title = "发布任务";
      this.addForm = {
        taskId: null,
        title: '',
        content: '',
        time: '',
      };
      this.getEmployee();
      this.addFormVisible = true;
    },

    editSubmit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true;
            //获取登录人的名字
            const logininfo = JSON.parse(localStorage.getItem("logininfo"));
            const username = logininfo.username;
            this.editForm.publisher=username;
            //时间格式转换
            this.editForm.deadline = this.formatDateForBackend(this.editForm.deadline);
            let para = Object.assign({}, this.editForm);
            this.$http.put("/task", para).then(res => {
              if (res.data.success) {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                this.$refs['editForm'].resetFields();
              } else {
                this.$message.error("系统繁忙，请稍后重试!!!【500】");
              }
              this.editLoading = false;
              this.editFormVisible = false;
              this.findTaskMag();
            });
          });
        }
      });
    },
    addSubmit() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true;
           //获取登陆人信息
            const logininfo = JSON.parse(localStorage.getItem("logininfo"));
            const username = logininfo.username;
            this.addForm.publisher=username;
            //时间格式转换
            this.addForm.deadline = this.formatDateForBackend(this.addForm.deadline);
            let para = Object.assign({}, this.addForm);
            this.$http.put("/task", para).then(res => {
              if (res.data.success) {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                this.$refs['addForm'].resetFields();
              } else {
                this.$message.error("系统繁忙，请稍后重试!!!【500】");
              }
              this.addLoading = false;
              this.addFormVisible = false;
              this.findTaskMag();
            });
          });
        }
      });
    },
    //获取所有执行人员=员工
    getEmployee() {
      this.$http.get("/employee").then(res => {
        if (res) {
          this.employees = res.data
        }
      })
    },
    findTaskMag() {
      this.$http.get("/task/findAllTaskInfo").then((res) => {
        if (res.data.success) {
          this.taskMags = res.data.resultObj;
        }

      })
    },

  },
  mounted() {
    this.findTaskMag();

  }
}

</script>

<!--<style scoped>-->
<style>
/*详情页面样式*/
.table-container {
  border: 1px solid #ddd; /* 表格容器边框样式，根据需要调整 */
  margin: 10px; /* 表格容器外边距，根据需要调整 */
  padding: 10px; /* 表格容器内边距，根据需要调整 */
}

.table-row {
  display: flex;
}

.table-cell {
  flex: 1;
  padding: 8px; /* 单元格内边距，根据需要调整 */
  border: 1px solid #ddd; /* 单元格边框样式，根据需要调整 */
}

.title-label,
.title-content,
.time-label,
.time-content,
.status-label,
.status-content,
.content-label,
.content-content,
.image-label,
.image-content,
.executive-label,
.executive-name {
  margin-right: 10px; /* 标签和内容之间的水平间距，根据需要调整 */
}
.custom-divider {
  border: 0.1px solid #e6f1fe; /* 调整线的宽度和颜色 */
}

.text {
  font-size: 14px;
}
.item {
  margin-bottom: 18px;
}
.info-item {
  margin-bottom: 10px; /* 调整上下间距 */
}
.el-form-item-title {

  align-items: baseline;
  margin-bottom: 1px;
}
.el-form-item-content {
  max-height: 80px; /* 控制最大高度 */
  overflow: hidden;
  flex-direction: column;
  margin-bottom: 1px;
}
.content-text{

  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
  max-height: 60px; /* 控制最大高度 */
  cursor: pointer;
  line-height:1.5em;
  margin-top: 10px;
}
.content-text::before {
  content: "..."; /* 省略号 */
  position: absolute;
  bottom: 0;
  right: 0;
  background: white; /* 背景色，根据实际情况调整 */
}
.el-form-item-people{
  margin-bottom: 0px;
  margin-top: 2px;

}
.el-form-item-time{
  height: 10px ;
  margin-top: 0px;
  margin-bottom: 3px;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.horizontal-menu {
  display: flex;
  flex-direction: row;
  justify-content: space-between; /* 调整按钮之间的间距 */
}

.dropdown-button {
  margin-top: 1px;
  margin-left: calc(75% ); /* 将按钮推到右侧 */

}
.task-list {
  list-style: none;
  margin: 0;
  padding: 0;
}

.task-item {
  box-sizing: border-box;
  width: calc(33.33% - 20px); /* 将宽度设置为三分之一减去填充 */
  float: left;
  margin: 10px;
}

.box-card {
  width: 100%;
  overflow: hidden;/* 溢出隐藏 */
  height: 280px;
  align-items: flex-start;
}

</style>